package com.paypalpay.controller.pay;

import com.paypalpay.entity.common.UserboundPaymentOrder;
import com.paypalpay.entity.pay.OceanPaymentRequestParam;
import com.paypalpay.entity.pay.OceanpayNotificationpaymentResults;
import com.paypalpay.service.OceanpayNotificationpaymentService;
import com.paypalpay.service.UserboundPaymentOrderService;
import com.paypalpay.util.pay.OceanpaymentUtil;
import com.paypalpay.util.wx.HMACSHA256;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * 钱海支付回调
 *
 * @author lm
 * @date 2018/8/31
 */
@Controller
@RequestMapping("/oceanPayment")
public class OceanPaymentController {
    //OceanPay支付type=3
    private String payType = "3";

    private String secureCode = "";
    @Autowired
    private HttpSession session;
    @Autowired
    OceanpayNotificationpaymentService oceanpayNotificationpaymentService;

    @Resource
    private UserboundPaymentOrderService userboundPaymentOrderService;

    private static Logger logger = Logger.getLogger(OceanPaymentController.class);

    @CrossOrigin
    @RequestMapping(value = "/payocean")
    @ResponseBody
    public String paypalPay(OceanPaymentRequestParam param, HttpServletRequest request) {
        System.out.println("oceanpay支付请求的链接是：" + request.getRequestURL() + "?" + request.getQueryString());

        String deviceId = request.getParameter("deviceId");
        String deviceType = request.getParameter("deviceType");
        String paymentOrderId = request.getParameter("paymentOrderId");
        String partnerCode = request.getParameter("partnerCode");
        String packageCode = request.getParameter("partnerCode");
        String orderPeriod = request.getParameter("orderPeriod");
        //需要前端发这三个参数上来
        //支付金额
        String orderAmount = request.getParameter("amount");
        //支付货币
        String orderCurrency = request.getParameter("currencyCode");
        //订单号
        String orderNumber = request.getParameter("orderId");
        //订单备注
        String orderNotes = request.getParameter("orderNotes");
        //消费者名
        String billingFirstName = request.getParameter("billingFirstName");
        //消费者姓
        String billingLastName = request.getParameter("billingLastName");
        //消费者邮箱
        String billingEmail = request.getParameter("billingEmail");
        //消费者电话
        String billingPhone = request.getParameter("billingPhone");
        //消费者账单国家
        String billingCountry = request.getParameter("billingCountry");
        //消费者的城市
        String billingCity = request.getParameter("billingCity");
        //消费者的详细地址
        String billingAddress = request.getParameter("billingAddress");
        //消费者的邮编
        String billingZip = request.getParameter("billingZip");
        //根据返回的xml计算签名
        String signValue =
                "account=" + param.getAccount() +
                        "terminal=" + param.getTerminal() +
                        "backUrl=" + param.getBackUrl() +
                        "order_number=" + orderNumber +
                        "order_currency=" + orderCurrency +
                        "order_amount=" + orderAmount +
                        "billing_firstName=" + billingFirstName +
                        "billing_lastName=" + billingLastName +
                        "billing_email=" + billingEmail +
                        "secureCode=" + secureCode;

        signValue = HMACSHA256.sha256_HMAC(signValue, secureCode).toUpperCase();

        // 根据packageCode去查询一下当前用户购买的套餐名称，并且插入到数据库
        String packageName = "";
        System.out.println("packageCode是什么多少：" + packageCode);
        if (packageCode.contains(",") == true) {
            // 此情况说明packageCode有多个套餐
            String[] str = packageCode.split(",");
            for (int i = 0; i < str.length; i++) {
                String packages = str[i];
                packageName += userboundPaymentOrderService.getPackageNameByPackageCode(packages,partnerCode) + ",";
                System.out.println("取到的套餐名称：" + packageName);
            }
        } else {
            packageName = userboundPaymentOrderService.getPackageNameByPackageCode(packageCode,partnerCode);
            System.out.println("取到的套餐名称：" + packageName);
        }
        // 判断一下：openId和orderId同时存在时是有卡用户，没有orderId的是无卡用户
//        if (!orderNumber.equals("") && !"undefined".equals(orderNumber)) {
//            //非微信用户访问
//            // 有卡orderId不为空，temOrderId为空，openid为空
//            System.out.println("orderId不为空，temOrderId为空，标准有卡流程！");
//            UserboundPaymentOrder paymentOrder = new UserboundPaymentOrder();
//            paymentOrder.setDeviceId(deviceId);
//            paymentOrder.setDeviceType(deviceType);
//            paymentOrder.setPaymentOrderId(paymentOrderId);
//            paymentOrder.setPartnerCode(partnerCode);
//            paymentOrder.setPackageCode(packageCode);
//            paymentOrder.setPackageName(packageName);
//            paymentOrder.setOrderPeriod(orderPeriod);
//            paymentOrder.setOrderId(orderNumber);
//            paymentOrder.setAmount(orderAmount);
//            paymentOrder.setOrderCurrency(orderCurrency);
//            paymentOrder.setBillingFirstName(billingFirstName);
//            paymentOrder.setBillingLastName(billingLastName);
//            paymentOrder.setBillingEmail(billingEmail);
//            paymentOrder.setBillingPhone(billingPhone);
//            paymentOrder.setBillingCountry(billingCountry);
//            paymentOrder.setBillingCity(billingCity);
//            paymentOrder.setBillingAddress(billingAddress);
//            paymentOrder.setBillingZip(billingZip);
//            // 根据收到的deviceId去更新数据表，deviceId此时是有的，所以不能为null,openid为空
//            userboundPaymentOrderService.updateUserboundOceanPaymentOrder(paymentOrder);
//        }

        //准备给前端发参数回去
        Map<String, Object> maps = new HashMap<String, Object>();
        maps.put("account", param.getAccount());
        maps.put("terminal", param.getTerminal());
        maps.put("signValue", signValue);
        maps.put("backUrl", param.getBackUrl());
        maps.put("noticeUrl", param.getNoticeUrl());
        maps.put("methods", param.getMethods());
        maps.put("pages", param.getPages());
        maps.put("order_number", orderNumber);
        maps.put("order_currency", orderCurrency);
        maps.put("order_amount", orderAmount);
        maps.put("order_notes", orderNotes);
        maps.put("billing_firstName", billingFirstName);
        maps.put("billing_lastName", billingLastName);
        maps.put("billing_email", billingEmail);
        maps.put("billing_phone", billingPhone);
        maps.put("billing_country", billingCountry);
        maps.put("billing_city", billingCity);
        maps.put("billing_address", billingAddress);
        maps.put("billing_zip", billingZip);

        JSONObject jsonObject = JSONObject.fromObject(maps);
        // 3、将json对象转化为json字符串
        String jsonString = jsonObject.toString();
        System.out.println("返回的报文是：" + jsonString);
        return jsonString;
    }

    @RequestMapping(value = "/backUrl")
    public String backUrl(HttpServletRequest request, HttpServletResponse response) {
        String deviceId = (String) session.getAttribute("deviceId");
        String deviceType = (String) session.getAttribute("deviceType");

        try {
            logger.info("钱海支付回调获取数据开始");
            Map rMap = OceanpaymentUtil.getNotifyResult(request);

            logger.info("钱海支付回调notify获取的数据：" + rMap.get("resXml") + "");
            // 向微信输出处理结果，如果成功（SUCCESS），微信就不会继续调用了，否则微信会连续调用8次
            response.getWriter().write("receive-ok"); // 告诉微信服务器，我收到信息了，不要在通知我了

            logger.info("开始分析钱海回调数据:");

            String orderId = rMap.get("orderNumber") + "";
            String paymentAmount = rMap.get("orderAmount") + "";
            String paymentStatus = rMap.get("paymentStatus") + "";
            String responseType = rMap.get("responseType") + "";
            String account = rMap.get("account") + "";
            String terminal = rMap.get("terminal") + "";
            String signValue = rMap.get("signValue") + "";
            String methods = rMap.get("methods") + "";
            String orderCurrency = rMap.get("orderCurrency") + "";
            String orderNotes = rMap.get("orderNotes") + "";
            String cardNumber = rMap.get("cardNumber") + "";
            String paymentId = rMap.get("paymentId") + "";
            String paymentCountry = rMap.get("paymentCountry") + "";
            String paymentAuthType = rMap.get("paymentAuthType") + "";
            String paymentDetails = rMap.get("paymentDetails") + "";
            String paymentRisk = rMap.get("paymentRisk") + "";
            String paymentSolutions = rMap.get("paymentSolutions") + "";
            String authReason = rMap.get("authReason") + "";
            String orderOperator = rMap.get("orderOperator") + "";
            //交易记录表
            OceanpayNotificationpaymentResults results = new OceanpayNotificationpaymentResults();
            results.setResponseType(responseType);
            results.setAccount(account);
            results.setTerminal(terminal);
            results.setSignValue(signValue);
            results.setMethods(methods);
            results.setOrderNumber(orderId);
            results.setOrderCurrency(orderCurrency);
            results.setOrderAmount(paymentAmount);
            results.setOrderNotes(orderNotes);
            results.setCardNumber(cardNumber);
            results.setPaymentId(paymentId);
            results.setPaymentCountry(paymentCountry);
            results.setPaymentAuthType(paymentAuthType);
            results.setPaymentStatus(paymentStatus);
            results.setPaymentDetails(paymentDetails);
            results.setPaymentRisk(paymentRisk);
            results.setPaymentSolutions(paymentSolutions);
            results.setAuthReason(authReason);
            results.setOrderOperator(orderOperator);

            oceanpayNotificationpaymentService.insertPaymentResults(results);


            //下面的判断说明回调的支付结果是成功的
            if (orderId != null && orderId.length() > 0 && paymentStatus != null && paymentStatus.equals("1")) {
                logger.info("调用给北京回调支付通知的controller:");
                String partnerCode = "";
                return "/payNotify?orderId=" + orderId + "&deviceId=" + deviceId + "&deviceType=" + deviceType + "" + "&paymentAmount=" + paymentAmount + "" + "&payType=" + "2" + "" + "&partnerCode=" + partnerCode + "";
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @RequestMapping(value = "/noticeUrl")
    public String noticeUrl(HttpServletRequest request, HttpServletResponse response) {
        String deviceId = (String) session.getAttribute("deviceId");
        String deviceType = (String) session.getAttribute("deviceType");

        try {
            logger.info("钱海支付回调获取数据开始");
            Map rMap = OceanpaymentUtil.getNotifyResult(request);

            logger.info("钱海支付回调notify获取的数据：" + rMap.get("resXml") + "");
            // 向微信输出处理结果，如果成功（SUCCESS），微信就不会继续调用了，否则微信会连续调用8次
            response.getWriter().write("receive-ok"); // 告诉微信服务器，我收到信息了，不要在通知我了

            logger.info("开始分析钱海回调数据:");

            String orderId = rMap.get("orderNumber") + "";
            String paymentAmount = rMap.get("orderAmount") + "";
            String paymentStatus = rMap.get("paymentStatus") + "";
            String responseType = rMap.get("responseType") + "";
            String account = rMap.get("account") + "";
            String terminal = rMap.get("terminal") + "";
            String signValue = rMap.get("signValue") + "";
            String methods = rMap.get("methods") + "";
            String orderCurrency = rMap.get("orderCurrency") + "";
            String orderNotes = rMap.get("orderNotes") + "";
            String cardNumber = rMap.get("cardNumber") + "";
            String paymentId = rMap.get("paymentId") + "";
            String paymentCountry = rMap.get("paymentCountry") + "";
            String paymentAuthType = rMap.get("paymentAuthType") + "";
            String paymentDetails = rMap.get("paymentDetails") + "";
            String paymentRisk = rMap.get("paymentRisk") + "";
            String paymentSolutions = rMap.get("paymentSolutions") + "";
            String authReason = rMap.get("authReason") + "";
            String orderOperator = rMap.get("orderOperator") + "";
            //交易记录表
            OceanpayNotificationpaymentResults results = new OceanpayNotificationpaymentResults();
            results.setResponseType(responseType);
            results.setAccount(account);
            results.setTerminal(terminal);
            results.setSignValue(signValue);
            results.setMethods(methods);
            results.setOrderNumber(orderId);
            results.setOrderCurrency(orderCurrency);
            results.setOrderAmount(paymentAmount);
            results.setOrderNotes(orderNotes);
            results.setCardNumber(cardNumber);
            results.setPaymentId(paymentId);
            results.setPaymentCountry(paymentCountry);
            results.setPaymentAuthType(paymentAuthType);
            results.setPaymentStatus(paymentStatus);
            results.setPaymentDetails(paymentDetails);
            results.setPaymentRisk(paymentRisk);
            results.setPaymentSolutions(paymentSolutions);
            results.setAuthReason(authReason);
            results.setOrderOperator(orderOperator);

            oceanpayNotificationpaymentService.insertPaymentResults(results);


            //下面的判断说明回调的支付结果是成功的
            if (orderId != null && orderId.length() > 0 && paymentStatus != null && paymentStatus.equals("1")) {
                logger.info("调用给北京回调支付通知的controller:");

                return "forward:/payNotify?orderId=" + orderId + "&deviceId=" + deviceId + "&deviceType=" + deviceType + "" + "&paymentAmount=" + paymentAmount + "" + "&payType=" + "2" + "";
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
